using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Win32;
using Newtonsoft.Json;
using System.IO;
using ErpManager.WPF.Models;
using ErpManager.WPF.Services;

namespace ErpManager.WPF.ViewModels
{
    public class ProductViewModel : INotifyPropertyChanged
    {
        private readonly ApplicationDbContext _context;
        private readonly LogService _logService;
        private string _searchText = string.Empty;
        private Product? _selectedProduct;
        private string _newProductName = string.Empty;
        private string _errorMessage = string.Empty;
        private bool _isLoading;

        public ObservableCollection<Product> Products { get; } = new();

        public event PropertyChangedEventHandler? PropertyChanged;

        public string SearchText
        {
            get => _searchText;
            set
            {
                _searchText = value;
                OnPropertyChanged(nameof(SearchText));
                FilterProducts();
            }
        }

        public Product? SelectedProduct
        {
            get => _selectedProduct;
            set
            {
                _selectedProduct = value;
                OnPropertyChanged(nameof(SelectedProduct));
                OnPropertyChanged(nameof(IsProductSelected));
            }
        }

        public string NewProductName
        {
            get => _newProductName;
            set
            {
                _newProductName = value;
                OnPropertyChanged(nameof(NewProductName));
            }
        }

        public string ErrorMessage
        {
            get => _errorMessage;
            set
            {
                _errorMessage = value;
                OnPropertyChanged(nameof(ErrorMessage));
            }
        }

        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged(nameof(IsLoading));
            }
        }

        public bool IsProductSelected => SelectedProduct != null;

        public ICommand AddProductCommand { get; }
        public ICommand DeleteProductCommand { get; }
        public ICommand ImportProductsCommand { get; }
        public ICommand RefreshCommand { get; }

        public ProductViewModel(ApplicationDbContext context)
        {
            _context = context;
            _logService = new LogService(context, "system", "系统");
            AddProductCommand = new RelayCommand(async () => await AddProduct(), CanAddProduct);
            DeleteProductCommand = new RelayCommand(async () => await DeleteProduct(), () => IsProductSelected);
            ImportProductsCommand = new RelayCommand(async () => await ImportProducts());
            RefreshCommand = new RelayCommand(async () => await LoadProducts());

            // 初始加载产品列表
            _ = LoadProducts();
        }

        private async Task LoadProducts()
        {
            try
            {
                IsLoading = true;
                ErrorMessage = string.Empty;

                var products = await _context.Products
                    .OrderByDescending(p => p.CreateTime)
                    .ToListAsync();

                Products.Clear();
                foreach (var product in products)
                {
                    Products.Add(product);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = $"加载产品列表失败: {ex.Message}";
            }
            finally
            {
                IsLoading = false;
            }
        }

        private void FilterProducts()
        {
            if (string.IsNullOrWhiteSpace(SearchText))
            {
                _ = LoadProducts();
                return;
            }

            var filteredProducts = _context.Products
                .Where(p => p.ProductName.Contains(SearchText))
                .OrderByDescending(p => p.CreateTime)
                .ToList();

            Products.Clear();
            foreach (var product in filteredProducts)
            {
                Products.Add(product);
            }
        }

        private async Task AddProduct()
        {
            try
            {
                if (!CanAddProduct())
                {
                    return;
                }

                var product = new Product
                {
                    ProductName = NewProductName.Trim(),
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };

                _context.Products.Add(product);
                await _context.SaveChangesAsync();

                // 记录添加产品日志
                await _logService.LogOperationAsync("产品管理", "添加", $"添加产品：{product.ProductName}");

                Products.Insert(0, product);
                NewProductName = string.Empty;
                ErrorMessage = string.Empty;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"添加产品失败: {ex.Message}";
            }
        }

        private bool CanAddProduct()
        {
            return !string.IsNullOrWhiteSpace(NewProductName) &&
                   !Products.Any(p => p.ProductName == NewProductName.Trim());
        }

        private async Task DeleteProduct()
        {
            if (SelectedProduct == null)
            {
                return;
            }

            try
            {
                var productName = SelectedProduct.ProductName;
                _context.Products.Remove(SelectedProduct);
                await _context.SaveChangesAsync();

                // 记录删除产品日志
                await _logService.LogOperationAsync("产品管理", "删除", $"删除产品：{productName}");

                Products.Remove(SelectedProduct);
                SelectedProduct = null;
                ErrorMessage = string.Empty;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"删除产品失败: {ex.Message}";
            }
        }

        private async Task ImportProducts()
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "JSON files (*.json)|*.json|All files (*.*)|*.*",
                Title = "选择要导入的JSON文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    var jsonContent = await File.ReadAllTextAsync(openFileDialog.FileName);
                    var importData = JsonConvert.DeserializeObject<ImportProductData>(jsonContent);

                    if (importData?.Products == null || !importData.Products.Any())
                    {
                        ErrorMessage = "导入文件格式不正确或没有产品数据";
                        return;
                    }

                    var now = DateTime.Now;
                    var newProducts = importData.Products
                        .Where(p => !string.IsNullOrWhiteSpace(p.ProductName))
                        .Select(p => new Product
                        {
                            ProductName = p.ProductName.Trim(),
                            CreateTime = now,
                            UpdateTime = now
                        })
                        .ToList();

                    // 检查重复产品名
                    var existingNames = await _context.Products
                        .Select(p => p.ProductName)
                        .ToListAsync();

                    newProducts = newProducts
                        .Where(p => !existingNames.Contains(p.ProductName))
                        .ToList();

                    if (!newProducts.Any())
                    {
                        ErrorMessage = "没有新的产品需要导入";
                        return;
                    }

                    await _context.Products.AddRangeAsync(newProducts);
                    await _context.SaveChangesAsync();

                    foreach (var product in newProducts)
                    {
                        Products.Insert(0, product);
                    }

                    ErrorMessage = $"成功导入 {newProducts.Count} 个产品";
                }
                catch (Exception ex)
                {
                    ErrorMessage = $"导入产品失败: {ex.Message}";
                }
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class ImportProductData
    {
        public List<ImportProduct> Products { get; set; } = new();
    }

    public class ImportProduct
    {
        public string ProductName { get; set; } = string.Empty;
    }
}
